package com.lbs.jiepiaisi.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.Projection;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.AccountChaseCarAcitivty;
import com.lbs.jiepiaisi.activity.AlarmListActivity;
import com.lbs.jiepiaisi.activity.TracingActivity;
import com.lbs.jiepiaisi.activity.AccountUserInfoActivity;
import com.lbs.jiepiaisi.activity.HistoryTraceActivity;
import com.lbs.jiepiaisi.bean.EquipBean;
import com.lbs.jiepiaisi.bean.EquipmentEntity;
import com.lbs.jiepiaisi.bean.TrackEntity;
import com.lbs.jiepiaisi.biz.LocationBiz;
import com.lbs.jiepiaisi.biz.TrackBiz;
import com.lbs.jiepiaisi.parser.trackAccountParser;
import com.lbs.jiepiaisi.view.WaitingDialogControll;
import com.luck.picture.lib.tools.ScreenUtils;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.request.base.Request;

import java.util.ArrayList;
import java.util.List;

public class AggregationUtils implements AMap.OnCameraChangeListener,
        AMap.InfoWindowAdapter, AMap.OnMarkerClickListener,
        AMap.OnMapClickListener ,AMap.OnMapLoadedListener, GeocodeSearch.OnGeocodeSearchListener {

    private ArrayList<Cluster> mClusters = new ArrayList<>();   //聚合点

    private List<Marker> allMarker = new ArrayList<>(); //所有的marker

    private Marker clickMarker; //当前点击的marker

    private float zoom;   //当前放大缩小程度

    private int aggregationRadius=100;//聚合半径

    private double mClusterDistance;    //聚合范围

    private List<ClusterItem> allPoints = new ArrayList<>(); //所有的点

    private Context context;

    private AMap aMap;

    private TextureMapView mapView;

    //=============================测试
    private boolean isUpdateCluster = true;

    private View infoWindow;

    private List<ClusterItem> clusterItems = new ArrayList<>();

    List<EquipBean.Result.Items> items;
    private EquipBean.Result.Items itemNew;


    private LinearLayout liner_info_below, liner_info_more, liner_history, liner_navi,
            liner_reposition, liner_track, liner_notice, liner_user_content;

    private TextView tv_driverName, tv_eqno, tv_flag, tv_time, tv_dress;

    private int possion = 0;

    private static int flag=0;//infowindow点击更多切换按钮状态

    //北京经纬度
    private LatLng bjLatLng = new LatLng(39.894914,116.322062);
    //请求的页数
    private int page = 1;

    private String possionTime;//当前定位时间

    private GeocodeSearch geocodeSearch;//逆地理编码转换对象

    private String addressName;//当前地址

    //=============================测试
    public void setContext(Context context) {
        this.context = context;
    }

    /**
     * 设置所有的点
     * @param allPoints
     */
    public void setAllPoints(List<ClusterItem> allPoints) {
        this.allPoints = allPoints;
    }

    public void setaMap(AMap aMap, TextureMapView mapView, List<EquipBean.Result.Items> items) {
        this.aMap = aMap;
        this.mapView = mapView;
        this.items = items;
        zoom = aMap.getCameraPosition().zoom;
        aMap.setInfoWindowAdapter(this);
        aMap.setOnCameraChangeListener(this);
        aMap.setOnMarkerClickListener(this);
        aMap.setOnMapClickListener(this);
        aMap.setOnMapLoadedListener(this);

        //aMap.moveCamera(CameraUpdateFactory.zoomTo(3));
        //moveMapToPosition(bjLatLng);
    }

    /** 清空地图上的指定的Marker*/
    //删除指定Marke
    public void clearMarkers() {
        //获取地图上所有Marker
        // aMap.clear();// 定位蓝点也会删除
        allPoints.clear();
        mClusters.clear();

        List<Marker> mapScreenMarkers = aMap.getMapScreenMarkers();
        for (int i = 0; i < mapScreenMarkers.size(); i++) {
            Marker marker = mapScreenMarkers.get(i);
            if (marker.getObject() instanceof Cluster) {
                marker.remove();//移除当前Marker
            }
        }
    }


    /**
     * 显示所有的点
     */
    public void showPoint(){
        assignClusters();

        //画圆
//        for (int i=0;i<mClusters.size();i++){
//            Cluster cluster = mClusters.get(i);
//
//            if(clickMarker!=null){
//                if(clickMarker.getPosition().latitude==cluster.getCenterLatLng().latitude&&clickMarker.getPosition().longitude==cluster.getCenterLatLng().longitude){
//                    allMarker.add(clickMarker);
//                    continue;
//                }
//            }
//            MarkerOptions markerOptions = new MarkerOptions();
//            markerOptions.anchor(0.5f, 0.5f).icon(getBitmapDes(cluster.mClusterItems.size())).position(cluster.mLatLng).title("...");
//
//            Marker marker = aMap.addMarker(markerOptions);
//            marker.setInfoWindowEnable(true);
//            marker.setObject(cluster);
//            allMarker.add(marker);
//        }

        //====================================测试
        for (int i=0;i<mClusters.size();i++){
            Cluster cluster = mClusters.get(i);
            if(clickMarker!=null){
                if(clickMarker.getPosition().latitude==cluster.getCenterLatLng().latitude&&clickMarker.getPosition().longitude==cluster.getCenterLatLng().longitude){
                    allMarker.add(clickMarker);
                    continue;
                }
            }
            if(cluster.getClusterItems().size() == 1){
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions
                        .anchor(0.5f, 0.5f)
                        .icon(getBitmapDesOnePoint(cluster.mClusterItems.get(0).latLng))
                        .position(cluster.mLatLng);
                Marker marker = aMap.addMarker(markerOptions);
                marker.setInfoWindowEnable(true);
                marker.setObject(cluster);
                allMarker.add(marker);

            }else {
                MarkerOptions markerOptions = new MarkerOptions();
                markerOptions.anchor(0.5f, 0.5f).icon(getBitmapDes(cluster.mClusterItems.size())).position(cluster.mLatLng).title("...");
                Marker marker = aMap.addMarker(markerOptions);
                marker.setInfoWindowEnable(true);
                marker.setObject(cluster);
                allMarker.add(marker);
            }
        }

        //====================================测试
    }

    /**
     * 对点进行聚合
     */
    private void assignClusters() {
        //算出聚合点
        mClusterDistance = aMap.getScalePerPixel()*aggregationRadius;

        //屏幕范围
        LatLngBounds visibleBounds = aMap.getProjection().getVisibleRegion().latLngBounds;

        //循环所有点
        for (int i=0;i<allPoints.size();i++) {
            LatLng latlng = allPoints.get(i).latLng;

            //判断当前点是否在可视范围内
            if (visibleBounds.contains(latlng)) {
                //获取聚合点
                Cluster cluster = getCluster(latlng,mClusters);

                //判断聚合点是否为空
                if (cluster != null) {
                    //不为空则直接加入到聚合点内
                    cluster.addClusterItem(latlng,allPoints.get(i).address,allPoints.get(i).id);
                } else {
                    //为空则创建聚合点
                    cluster = new Cluster(latlng);
                    mClusters.add(cluster);
                    cluster.addClusterItem(latlng,allPoints.get(i).address,allPoints.get(i).id);
                }

            }
        }
    }

    /**
     * 判断当前点附近是否有聚合点
     *
     * @param latLng
     * @return
     */
    private Cluster getCluster(LatLng latLng, List<Cluster> clusters) {
        //循环所有的聚合点
        for (Cluster cluster : clusters) {
            LatLng clusterCenterPoint = cluster.getCenterLatLng();
            //计算当前点和聚合点之间的距离
            double distance = AMapUtils.calculateLineDistance(latLng, clusterCenterPoint);

            //如果距离在规定点范围内，则说明有聚合点
            if (distance < mClusterDistance) {
                return cluster;
            }
        }
        return null;
    }

    /**
     * 获取每个聚合点的绘制样式
     */
    private BitmapDescriptor getBitmapDes(int num) {

        float radius = Math.round(46 * ScaledValueForValue(num));

        TextView textView = new TextView(context);
        textView.setText(String.valueOf(num));
        textView.setGravity(Gravity.CENTER);
        textView.setTextColor(Color.WHITE);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 12);
        textView.setBackground(getDrawAble(radius));
        return BitmapDescriptorFactory.fromView(textView);
    }

    /* 根据count计算annotation的scale. */
    private float ScaledValueForValue(int value)
    {
        return (float) (1.0 / (1.0 + Math.exp(-1 * 0.3 * Math.pow(value, 0.4))));
    }

    private Drawable getDrawAble(float r) {
        int radius = ScreenUtils.dip2px(context, r);
        Drawable bitmapDrawable = new BitmapDrawable(null, drawCircle(radius));
        return bitmapDrawable;
    }

    private Bitmap drawCircle(int radius) {
        Bitmap bitmap = Bitmap.createBitmap(radius * 2, radius * 2,
                Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        Paint paint0 = new Paint();
        paint0.setColor(Color.WHITE);
        paint0.setStyle(Paint.Style.FILL);
        canvas.drawCircle(radius,radius,radius-7,paint0);

        Paint paint1 = new Paint();
        paint1.setColor(Color.GRAY);
        paint1.setStyle(Paint.Style.STROKE);
        paint1.setStrokeWidth(ScreenUtils.dip2px(context, 1.f));
        canvas.drawCircle(radius,radius,radius-7,paint1);

        Paint paint2 = new Paint();
        paint2.setAntiAlias(true);
        paint2.setColor(Color.RED);
        paint2.setStyle(Paint.Style.FILL);
        canvas.drawCircle(radius,radius,radius - 19,paint2);

        return bitmap;
    }

//    private Bitmap drawCircle(int radius) {
//        Bitmap bitmap = Bitmap.createBitmap(radius * 2, radius * 2,
//                Bitmap.Config.ARGB_8888);
//        Canvas canvas = new Canvas(bitmap);
//        Paint paint1 = new Paint();
//
//        paint1.setColor(Color.parseColor("#2dbdff"));
//        paint1.setAlpha(160);
//        canvas.drawCircle(radius,radius,radius-10,paint1);
//
//        Paint paint = new Paint();
//        paint.setAntiAlias(true);
//        paint.setColor(Color.parseColor("#0386ba"));
//        paint.setStyle(Paint.Style.STROKE);  //设置画笔为空心
//        paint.setStrokeWidth( ScreenUtils.dip2px(context, 4)); //设置线宽
//        canvas.drawCircle(radius,radius,radius-10,paint);
//
//        return bitmap;
//    }

    /**
     * 点击地图
     * @param latLng
     */
    @Override
    public void onMapClick(LatLng latLng) {
        clickMarker.hideInfoWindow();
    }

    /**
     * 地图移动
     * @param cameraPosition
     */
    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        if(zoom!=cameraPosition.zoom){
            clickMarker = null;
            zoom = cameraPosition.zoom;
        }
    }
    /**
     * 地图移动完成
     * @param cameraPosition
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {

        if(isUpdateCluster){
            for (Marker marker:allMarker){
                if(clickMarker!=null&&clickMarker.getPosition().longitude==marker.getPosition().longitude&&clickMarker.getPosition().latitude==marker.getPosition().latitude){
                    continue;
                }

                marker.hideInfoWindow();
                marker.remove();
            }

            allMarker = new ArrayList<Marker>();
            mClusters = new ArrayList<Cluster>();
            mClusterDistance = aMap.getScalePerPixel()*aggregationRadius;//聚合的范围半径
            showPoint();

            //如果点击的marker 不再可是范围内
            LatLngBounds visibleBounds = aMap.getProjection().getVisibleRegion().latLngBounds;
            if(clickMarker != null){
                if(!visibleBounds.contains(clickMarker.getPosition())){
                    clickMarker.hideInfoWindow();
                    clickMarker.remove();
                    clickMarker=null;
                }
            }

        }else {
            isUpdateCluster = true;
        }
    }
    /**
     * marker 点击
     * @param
     */
    @Override
    public boolean onMarkerClick(Marker marker) {
        clickMarker = marker;
        //marker.showInfoWindow();
        //返回:true 表示点击marker 后marker 不会移动到地图中心；返回false 表示点击marker 后marker 会自动移动到地图中心
        //return true;

        /*=========t=========*/
        if(marker.getObject() == null){
            return true;
        }
        Cluster cluster= (Cluster) marker.getObject();
        if(cluster != null  && cluster.getClusterItems().size() > 1){
            isUpdateCluster = true;
//            LatLngBounds.Builder builder = new LatLngBounds.Builder();
//            for (ClusterItem clusterItem : clusterItems) {
//                builder.include(clusterItem.latLng);
//            }
//            LatLngBounds latLngBounds = builder.build();
//            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,((int)aMap.getCameraPosition().zoom) + 1));
            //aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(latLngBounds,((int)aMap.getCameraPosition().zoom) + 1));
            zoom++;
            aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
            moveMapToPosition(cluster.getCenterLatLng());
            upDateMap();
            return true;
        } else {
            isUpdateCluster = false;
            if(marker.isInfoWindowShown()){
                marker.hideInfoWindow();
                return true;
            } else {
                if(infoWindow != null){
                    infoWindow = getInfoView(marker.getPosition());
                }
                marker.showInfoWindow();
            }

            moveMapToPositionAndShowInfoView(marker);
            aMap.setPointToCenter(WindowSizeUtil.getWidth(context) / 2, WindowSizeUtil.getHeight(context) / 5 * 4);
            return true;
        }
        /*=========t=========*/
    }

    /**
     * 自定义弹框
     * @param marker
     * @return
     */
    @Override
    public View getInfoWindow(Marker marker) {
        //View infoContent = LayoutInflater.from(context).inflate(R.layout.custom_info_window, null);
        //render(infoContent,marker);
        //return infoContent;

        //===================================测试
        if(infoWindow == null) {
            infoWindow = getInfoView(marker.getPosition());
        }
        return infoWindow;
        //===================================测试
    }

    private View getInfoView(LatLng latLng) {
//        if(infoWindow == null){
//            View view = LayoutInflater.from(context).inflate(R.layout.layout_marker_infowindow, null);
//            infoWindow = view;
//        }
//        return infoWindow;
        //==============================测试
        for(int i = 0; i<items.size(); i++){
            if(latLng.latitude == items.get(i).getPoint().getLat()
                    && latLng.longitude == items.get(i).getPoint().getLng()){
                possion = i;
            }
        }

        if(infoWindow == null){
            final View view = LayoutInflater.from(context).inflate(R.layout.layout_marker_infowindow, null);
            infoWindow = view;
            //不显示更多选项
            liner_info_below = view.findViewById(R.id.liner_info_below);
            liner_info_more = view.findViewById(R.id.liner_info_more);
            liner_history = view.findViewById(R.id.liner_history);
            liner_navi = view.findViewById(R.id.liner_navi);
            liner_reposition = view.findViewById(R.id.liner_reposition);
            liner_track = view.findViewById(R.id.liner_track);
            liner_notice = view.findViewById(R.id.liner_notice);
            liner_user_content = view.findViewById(R.id.liner_user_content);
            tv_driverName = view.findViewById(R.id.tv_driverName);
            tv_eqno = view.findViewById(R.id.tv_eqno);
            tv_flag = view.findViewById(R.id.tv_flag);
            tv_time = view.findViewById(R.id.tv_time);
            tv_dress = view.findViewById(R.id.tv_dress);


            liner_info_below.setVisibility(View.GONE);


            EquipBean.Result.Items item = items.get(possion);

            //设置车主姓名
            String ownerName = item.getOwnerName();
            if (ownerName == null) {
                ownerName = item.getEqModel() + "-" + item.getEqNo().substring(10);
            }
            tv_driverName.setText(item.getOwnerName());
            //设置设备编号
            tv_eqno.setText(item.getEqNo());

            //存储设备状态
            // 2019-12-30 16:52
            // mSharePreference.put(Constant.ACCOUNT_STATUS,items.get(possion).getStatus());
            //存储车主姓名
            // 2019-12-30 16:52
            // mSharePreference.put(Constant.ACCOUNT_NAME,items.get(possion).getOwnerName());

            if("2".equals(item.getStatus())){
                tv_flag.setText("离线");
            }else if("3".equals(item.getStatus())){
                tv_flag.setText("未启用");
            }else {
                tv_flag.setText("在线");
            }

            // 定位时间
            tv_time.setText(item.getPoint().getPositionTime());
            // 状态
            tv_flag.setText(item.getCnStatus().replaceAll(" ",""));
            // 定位位置
            //tv_dress.setText(items.get(possion).getInstallerPosition().split("\\(")[0]);
            tv_dress.setText(item.getInstallerPosition());

            /**
             * 逆地理位置
             */
            //存储当前地址（通过经纬度转换为地理位置）
            double lat=items.get(possion).getPoint().getLat();
            double lng=items.get(possion).getPoint().getLng();
            LatLonPoint latLonPoint=new LatLonPoint(lat,lng);
            geocodeSearch=new GeocodeSearch(context);
            geocodeSearch.setOnGeocodeSearchListener(this);

            // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
            RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,GeocodeSearch.AMAP);
            geocodeSearch.getFromLocationAsyn(query);

            /**
             * 设置按钮点击事件
             */
            //更多
            liner_info_more.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(flag==0){//点击全选
                        flag=1;
                        //显示更多选项
                        liner_info_below.setVisibility(View.VISIBLE);
                    }else{
                        flag=0;
                        //显示更多选项
                        liner_info_below.setVisibility(View.GONE);
                    }
                }
            });
            //历史轨迹
            liner_history.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ButtonUtil.isFastClick()) {
                        // IntentUtil.gotoActivity(mContext,HistoryTraceActivity.class,false,map);
                        Intent intent = new Intent();
                        intent.putExtra("eqNo", items.get(possion).getEqNo());//存入当前设备
                        intent.putExtra("carName",items.get(possion).getOwnerName());//存入当前车主姓名
                        intent.setClass(context, HistoryTraceActivity.class);
                        context.startActivity(intent);
                    }
                }
            });
            //一键追车
            liner_navi.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ButtonUtil.isFastClick()) {
                        Intent intent=new Intent(context,AccountChaseCarAcitivty.class);
                        TrackEntity data = new TrackEntity();
                        TrackEntity.Result dataResult = new TrackEntity.Result();
                        dataResult.setGdLat(items.get(possion).getPoint().getLat());
                        dataResult.setGdLng(items.get(possion).getPoint().getLng());
                        ArrayList<TrackEntity.Result> results = new ArrayList<>();
                        results.add(dataResult);
                        data.setResults(results);
                        intent.putExtra(Constant.ACCOUNT_NAVIGATION, data);
                        context.startActivity(intent);
                    }
                }
            });
            //重新定位
            liner_reposition.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (ButtonUtil.isFastClick()) {
                        WaitingDialogControll.showWaitingDialog(context);
                        //开启刷新状态
                        closeShowDialog(clickMarker);
                        final TrackBiz trackBiz=new TrackBiz();
                        //trackBiz.trackBiz(items.get(possion).getEqNo(),items.get(possion),null,Constant.ACCOUNT_TRACK,true);

                        OkGo.<String>post(UrlUtil.ACCOUNT_TRACK)
                                .tag(this)
                                .retryCount(3)
                                .params("eqNo",items.get(possion).getEqNo())
                                .execute(new StringCallback() {
                                    @Override
                                    public void onStart(Request<String, ? extends Request> request) {
                                        super.onStart(request);
                                        WaitingDialogControll.showWaitingDialog(context);
                                    }

                                    @Override
                                    public void onSuccess(com.lzy.okgo.model.Response<String> response) {
                                        if(response.body() == null){
                                            return;
                                        }
                                        if(response.body().toString().contains("\"status\":1") && page == 1){
                                            WaitingDialogControll.dismissWaitingDialog();
                                            return;
                                        }
                                        TrackEntity trackEntity=new TrackEntity();
                                        try{
                                            //返回结果
                                            String jsonString = response.body();
                                            Log.e("track",jsonString);
                                            trackEntity= trackAccountParser.parser(jsonString);
                                            WaitingDialogControll.dismissWaitingDialog();
                                            itemNew = items.get(possion);
                                            if(trackEntity != null && trackEntity.getResults() != null &&  trackEntity.getResults().size() > 0){
                                                if(!trackEntity.getResults().get(0).getImportTime().equals("null")){
                                                    possionTime=trackEntity.getResults().get(0).getImportTime();
                                                }else{
                                                    possionTime="未上传定位时间";
                                                }
                                                if(infoWindow != null){
                                                    tv_time.setText(trackEntity.getResults().get(0).getImportTime());
                                                    ((TextView)infoWindow.findViewById(R.id.tv_post_type)).setText(trackEntity.getResults().get(0).getPostType());
                                                    String status = trackEntity.getResults().get(0).getStatus();
                                                    if("2".equals(status)){
                                                        tv_flag.setText("离线");
                                                    }else if("3".equals(status)) {
                                                        tv_flag.setText("未启用");
                                                    }else {
                                                        tv_flag.setText("在线");
                                                    }
                                                    new LocationBiz().getAddRessWithLatAndLng(trackEntity.getResults().get(0).getGdLat(),trackEntity.getResults().get(0).getGdLng(),Constant.ACCOUNT_LAT_LNG);
//                                                    if(itemNew != null) {
//                                                        itemNew.getPoint().setLat(trackEntity.getResults().get(0).getGdLat());
//                                                        itemNew.getPoint().setLng(trackEntity.getResults().get(0).getGdLng());
//                                                        itemNew.getPoint().setRoate(trackEntity.getResults().get(0).getDir());
//                                                        int position = delItemOld(itemNew);
//                                                        items.add(position,itemNew);
//                                                        markCarsOnMap(items,false);
//                                                        messageMarker = poiOverlay.getMarkerByPosition(position);
//                                                        ShowDialog(clickMarker);
//                                                        aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
//                                                        aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(trackEntity.getResults().get(0).getGdLat(), trackEntity.getResults().get(0).getGdLng())));
//                                                    }
                                                    //upDateMap();
                                                    clickMarker.showInfoWindow();
                                                }
                                            }

                                        }catch (Exception e){
                                            trackEntity.setStatus(Constant.STATUS_NETWORK_ERROR);
                                            e.printStackTrace();
                                        }
                                    }

                                    @Override
                                    public void onError(com.lzy.okgo.model.Response<String> response) {
                                        WaitingDialogControll.dismissWaitingDialog();
                                    }
                                });

                    }
                }
            });
            //实时跟踪
            liner_track.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(ButtonUtil.isFastClick()){
                        // WaitingDialogControll.showWaitingDialog(mContext);
                        Intent intent = new Intent();
                        intent.putExtra("eqNo", items.get(possion).getEqNo());//存入当前设备
                        intent.putExtra("ownerName",items.get(possion).getOwnerName());
                        intent.setClass(context, TracingActivity.class);
                        context.startActivity(intent);
                    }
                }
            });
            //告警
            liner_notice.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(ButtonUtil.isFastClick()){
                        Intent intent=new Intent();
                        intent.putExtra("eqNo", items.get(possion).getEqNo());//存入当前设备编码
                        intent.putExtra("deptId",items.get(possion).getDeptId());//存入当前部门编码
                        intent.putExtra("eqName",items.get(possion).getOwnerName());//存入姓名
                        intent.setClass(context, AlarmListActivity.class);
                        context.startActivity(intent);
                    }
                }
            });

            //用户信息
            liner_user_content.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(ButtonUtil.isFastClick()){
                        Intent intent=new Intent();
                        intent.putExtra("eqNo", items.get(possion).getEqNo());//设备号
                        intent.putExtra("deptId",items.get(possion).getDeptId());//型号
                        intent.setClass(context, AccountUserInfoActivity.class);
                        context.startActivity(intent);

                    }
                }
            });
        }

        return infoWindow;
        //==============================测试
    }

    @Override
    public View getInfoContents(Marker marker) {
        return null;
    }


    /**
     * 自定义infowinfow窗口
     * @param
     * @param view
     */
//    public void render(View view,Marker marker) {
//        final Cluster cluster = (Cluster)marker.getObject();
//
//        ListView recyclerView = (ListView) view.findViewById(R.id.listView);
//        recyclerView.setAdapter(new BaseAdapter() {
//            @Override
//            public int getCount() {
//                return cluster.mClusterItems.size();
//            }
//
//            @Override
//            public Object getItem(int position) {
//                return null;
//            }
//
//            @Override
//            public long getItemId(int position) {
//                return 0;
//            }
//
//            @Override
//            public View getView(int position, View convertView, ViewGroup parent) {
//                View view = LayoutInflater.from(context).inflate(R.layout.item_behavior, parent,false);
//                TextView tv = (TextView) view.findViewById(R.id.text_item);
//                tv.setText(cluster.mClusterItems.get(position).address);
//                return view;
//            }
//        });
//        setListViewHeightBasedOnChildren(recyclerView);
//
//    }

    /**
     * 切换页面的时候调用
     */
    public void resetData(){
        if(clickMarker!=null){
            clickMarker.hideInfoWindow();
        }
        allPoints.clear();
    }

    /**
     * 动态设置listview 的高度
     * @param listView
     */
//    public void setListViewHeightBasedOnChildren(ListView listView) {
//
//        //获取listview的适配器
//        ListAdapter listAdapter = listView.getAdapter(); //item的高度
//
//        if (listAdapter == null) {
//            return;
//        }
//        int totalHeight = 0;
//
//        for (int i = 0; i < listAdapter.getCount(); i++) {
//            View items = listAdapter.getView(i, null, listView);
//
//            items.measure(0, 0); //计算子项View 的宽高 //统计所有子项的总高度
//            totalHeight += items.getMeasuredHeight()+listView.getDividerHeight();
//        }
//
//        ViewGroup.LayoutParams params = listView.getLayoutParams();
//        int maxHeight=ScreenUtils.dip2px(context,100);
//        if(totalHeight>maxHeight){
//            params.height=maxHeight;
//        }else{
//            params.height = totalHeight;
//        }
//
//        listView.setLayoutParams(params);
//    }

    /**
     *
     * 聚合点
     */
    public class Cluster {
        //聚合点位置
        private LatLng mLatLng;

        private Marker mMarker;

        //聚合点中列表
        private List<ClusterItem> mClusterItems = new ArrayList<ClusterItem>();

        Cluster( LatLng latLng) {
            mLatLng = latLng;
        }

        LatLng getCenterLatLng() {
            return mLatLng;
        }

        public List<ClusterItem> getClusterItems() {
            return mClusterItems;
        }

        void addClusterItem(LatLng latLng ,String address,String id) {
            ClusterItem clusterItem=new ClusterItem();
            clusterItem.latLng=latLng;
            clusterItem.address=address;
            clusterItem.id=id;
            mClusterItems.add(clusterItem);
        }
    }

    public static class ClusterItem{
        public LatLng latLng;
        public String address;
        public String id;
    }

    /**
     * by moos on 2018/01/12
     * func:移动地图视角到某个精确位置
     * @param latLng 坐标
     */
    private void moveMapToPosition(LatLng latLng) {
        zoom = zoom +1;
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(
                new CameraPosition(
                        latLng,//新的中心点坐标
                        zoom,    //新的缩放级别
                        0,     //俯仰角0°~45°（垂直与地图时为0）
                        0      //偏航角 0~360° (正北方为0)
                ));
        aMap.animateCamera(cameraUpdate, 300, new AMap.CancelableCallback() {
            @Override
            public void onFinish() {


            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * by songdehua on 2018/07/02
     * @param marker 坐标
     */
    private void moveMapToPositionAndShowInfoView(final Marker marker) {
        CameraUpdate cameraUpdate = CameraUpdateFactory.newCameraPosition(
                new CameraPosition(
                        marker.getPosition(),//新的中心点坐标
                        zoom,     //新的缩放级别
                        0,     //俯仰角0°~45°（垂直与地图时为0）
                        0      //偏航角 0~360° (正北方为0)
                ));
        aMap.animateCamera(cameraUpdate, 300, new AMap.CancelableCallback() {
            @Override
            public void onFinish() {
                marker.showInfoWindow();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    /**
     * by moos on 2017/09/05
     * func:获取屏幕中心的经纬度坐标
     * @return
     */
    public LatLng getMapCenterPoint() {
        int left = mapView.getLeft();
        int top = mapView.getTop();
        int right = mapView.getRight();
        int bottom = mapView.getBottom();
        // 获得屏幕点击的位置
        int x = (int) (mapView.getX() + (right - left) / 2);
        int y = (int) (mapView.getY() + (bottom - top) / 2);
        Projection projection = aMap.getProjection();
        LatLng pt = projection.fromScreenLocation(new Point(x, y));

        return pt;
    }

    public void upDateMap(){
        if(isUpdateCluster){
            for (Marker marker:allMarker){
                if(clickMarker!=null&&clickMarker.getPosition().longitude==marker.getPosition().longitude&&clickMarker.getPosition().latitude==marker.getPosition().latitude){
                    continue;
                }

                marker.hideInfoWindow();
                marker.remove();
            }

            allMarker = new ArrayList<Marker>();
            mClusters = new ArrayList<Cluster>();
            mClusterDistance = aMap.getScalePerPixel()*aggregationRadius;//聚合的范围半径
            showPoint();

            //如果点击的marker 不再可是范围内
            LatLngBounds visibleBounds = aMap.getProjection().getVisibleRegion().latLngBounds;
            if(!visibleBounds.contains(clickMarker.getPosition())){
                clickMarker.hideInfoWindow();
                clickMarker.remove();
                clickMarker=null;
            }
        }else {
            isUpdateCluster = true;
        }
    }

    /**
     * 为单个点添加聚合点样式
     */
    private BitmapDescriptor getBitmapDesOnePoint(LatLng latLng) {
        //BitmapDescriptor bitmapDescriptor = mLruCache.get(num);
        int pos = 0;
        for(int i = 0; i<items.size(); i++){
            if(items.get(i).getPoint().getLat() == latLng.latitude
                    && items.get(i).getPoint().getLng() == latLng.longitude){
                pos = i;
            }
        }

        View view = View.inflate(context, R.layout.layout_marker, null);
        ImageView iv = (ImageView) view.findViewById(R.id.iv_marker);
        TextView tv_carname = (TextView) view.findViewById(R.id.tv_carname);

        EquipBean.Result.Items item = items.get(pos);

        //设置车主姓名
        String ownerName = item.getOwnerName();
        if (ownerName == null || ownerName.equals("")) {
            ownerName = item.getEqModel() + "-" + item.getEqNo().substring(10);
        }
        tv_carname.setText(ownerName);
        //设置图片类型
        if(item.getStatus().equals("2")){//离线
            iv.setImageResource(R.mipmap.icon_hui_daohang);
        } else {
            iv.setImageResource(R.mipmap.icon_daohang);
        }
        //设置角度
        float dir = item.getPoint().getDir();
        iv.setRotation(dir);
        //bitmapDescriptor = BitmapDescriptorFactory.fromView(view);
        //mLruCache.put(num, bitmapDescriptor);
        return BitmapDescriptorFactory.fromView(view);
    }

    public void closeShowDialog(Marker marker){
        // 设置地图中心点在屏幕的位置
        if (marker != null && marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        }
    }

    @Override
    public void onMapLoaded() {

    }

    public void ShowDialog(Marker marker){
        // 设置地图中心点在屏幕的位置
        clickMarker = marker;
        if(marker == null){
            return;
        }
        if (marker.isInfoWindowShown()) {
            marker.hideInfoWindow();
        }else{
            marker.showInfoWindow();
            aMap.setPointToCenter(WindowSizeUtil.getWidth(context) / 2, WindowSizeUtil.getHeight(context) / 5 * 4);
            marker.showInfoWindow();
            aMap.moveCamera(CameraUpdateFactory.zoomTo(zoom));
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(new LatLng(marker.getPosition().latitude, marker.getPosition().longitude)));
        }
    }

    private int delItemOld(EquipmentEntity.Result.Item item){
        for(int i = 0; i < items.size() ;i ++){
            if(items.get(i).getEqNo().equals(item.getEqNo())){
                items.remove(i);
                return i;
            }
        }
        return  0;
    }

    /**
     * 通过经纬度转化为地理位置
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        Log.e("eeeiii","逆地理解析");
        if (rCode == 1000) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress() + "附近";
                tv_dress.setText(addressName);
                Log.e("eeeiii","逆地理成功");
                Log.e("eeeiii","逆地理成功 = "+addressName);
            } else {
                addressName = "当前地址获取失败";
                Log.e("eeeiii","逆地理失败0");
            }
        } else {
            addressName = "当前地址获取失败";
            Log.e("eeeiii","逆地理失败1");
        }
    }

    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {

    }
}
